package com.ktjiaoyu.travelaiagent.rag;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class TravelVectorStoreConfig {

    // 注入我们自己编写的DocumentReader
    @Resource
    private DocumentReader travelMarkdownDocumentReader;

    /**
     * 构建向量库
     * @param dashscopeEmbeddingModel 灵积EmbeddingModel大模型
     * @return
     */
    @Bean
    public VectorStore travelVectorStore(EmbeddingModel dashscopeEmbeddingModel){
        // 读取文档
        List<Document> documents = travelMarkdownDocumentReader.get();
        // 构建向量库
        SimpleVectorStore vectorStore = SimpleVectorStore
                .builder(dashscopeEmbeddingModel).build();
        // 加载文档到向量库
        vectorStore.doAdd(documents);
        return vectorStore;
    }
    /** 定义基于本地知识库的RAG Advisor对象 */
    @Bean
    public Advisor localRagAdvisor(VectorStore vectorStore){
        return new QuestionAnswerAdvisor(vectorStore);
    }

    @Value("${spring.ai.dashscope.api-key}")
    private String dashScopeApiKey;

    @Bean
    public Advisor cloudRagAdvisor(){
        DashScopeApi dashScopeApi = new DashScopeApi(dashScopeApiKey);
        // 定义平台知识库的名称
        final String KNOWLEDGE_INDEX = "旅游大师";
        // 构建文档检索选项，告知文档来源于哪个知识库
        DashScopeDocumentRetrieverOptions options =
                DashScopeDocumentRetrieverOptions.builder()
                    .withIndexName(KNOWLEDGE_INDEX)
                    .build();
        // 构建文档检索器
        DocumentRetriever documentRetriever =
                new DashScopeDocumentRetriever(dashScopeApi,options);
        // 构建向量检索增强顾问
        return RetrievalAugmentationAdvisor.builder()
                .documentRetriever(documentRetriever)
                .build();
    }
}
